package org.apache.servicecomb.fence.service;

import java.util.concurrent.CompletableFuture;

import org.apache.seata.core.context.RootContext;
import org.apache.servicecomb.core.Invocation;
import org.apache.servicecomb.core.filter.AbstractFilter;
import org.apache.servicecomb.core.filter.FilterNode;
import org.apache.servicecomb.core.filter.ProviderFilter;
import org.apache.servicecomb.swagger.invocation.Response;

public class SeataContextProviderFilter extends AbstractFilter implements ProviderFilter {
  @Override
  // after schedule and only work in blocking mode
  public int getOrder() {
    return ProviderFilter.PROVIDER_SCHEDULE_FILTER_ORDER + 10;
  }

  @Override
  public String getName() {
    return "seata-provider";
  }

  @Override
  public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) {
    String context = invocation.getContext(RootContext.KEY_XID);
    if (context != null) {
      RootContext.bind(context);
    }
    return nextNode.onFilter(invocation).whenComplete((r, e) -> RootContext.unbind());
  }
}
